//
//  FirstViewController.m
//  Birthday Reminder
//
//  Created by Andrei Marcu on 10/22/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FirstViewController.h"
#import "BirthdayItem.h"
#import "ContactsTools.h"
#import "DateTools.h"
#import "BirthdayItemCell.h"
#import "DetailedViewController.h"
#import "NotificationTools.h"

@interface FirstViewController (Private)

- (void)setupTableData;
- (void)sortData;

@end


@implementation FirstViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setupTableData];
    [birthdayTable reloadData];
    [NotificationTools updateNotificationsFromDictionary:tableData];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewDidUnload
{
    [birthdayTable release];
    birthdayTable = nil;
    [tableData removeAllObjects];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [super viewWillAppear:animated];
}

- (void)dealloc
{
    [birthdayTable release];
    [orderedKeys release];
    [tableData release];
    [super dealloc];
}

#pragma mark - Private methods

- (void)setupTableData {
    if (tableData == nil) {
        tableData = [[NSMutableDictionary alloc] init];
    }
    [tableData removeAllObjects];
    NSArray *contactsWithBirthdays = [ContactsTools getContactsArrayWithBirthdays];
    for (BirthdayItem *item in contactsWithBirthdays) {
        NSString *month = [DateTools getStringMonthFromDate:item.birthDate];
        NSMutableArray *monthArray = [tableData objectForKey:month];
        if (monthArray == nil) {
            monthArray = [[NSMutableArray alloc] init];
            [tableData setObject:monthArray forKey:month];
            [monthArray release];
        }
        [monthArray addObject:item];
    }
    [self sortData];
    
}

- (void)sortData {
    NSArray *keys = [tableData allKeys];
    for (NSString *key in keys) {
        NSArray *values = [tableData objectForKey:key];
        NSArray *sortedArray = [values sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            BirthdayItem *item1 = (BirthdayItem *)obj1;
            BirthdayItem *item2 = (BirthdayItem *)obj2;
            if ([DateTools getDayFromDate:item1.birthDate] < [DateTools getDayFromDate:item2.birthDate]) {
                return (NSComparisonResult)NSOrderedAscending;
            } else {
                return (NSComparisonResult)NSOrderedDescending;
            }
        }];
        [tableData setObject:sortedArray forKey:key];
    }
    NSMutableArray *remainingDaysArray = [[NSMutableArray alloc] init];
    for (NSString *key in keys) {
        NSArray *items = [tableData objectForKey:key];
        BirthdayItem *item = [items objectAtIndex:0];
        NSDate *nextBirthdate = [DateTools getNextBirthdayForDate:item.birthDate];
        [remainingDaysArray addObject:[NSString stringWithFormat:@"%d", [DateTools getNumberOfDaysFromDate:[NSDate date] toDate:nextBirthdate]]];
    }
    NSArray *nextBirthdaySortedArray = [remainingDaysArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSInteger item1 = [(NSString *)obj1 intValue];
        NSInteger item2 = [(NSString *)obj2 intValue];
        if (item1 < item2) {
            return (NSComparisonResult)NSOrderedAscending;
        } else {
            return (NSComparisonResult)NSOrderedDescending;
        }
    }];
    NSMutableArray *mutableKeys = [NSMutableArray arrayWithArray:[tableData allKeys]];
    NSMutableArray *newKeys = [[NSMutableArray alloc] init];
    for (int i = 0; i < [nextBirthdaySortedArray count]; ++i) {
        for (int j = 0; j < [remainingDaysArray count]; ++j) {
            if ([[nextBirthdaySortedArray objectAtIndex:i] isEqualToString:[remainingDaysArray objectAtIndex:j]]) {
                [newKeys addObject:[mutableKeys objectAtIndex:j]];
            }
        }
    }
    orderedKeys = [newKeys retain];
    [newKeys release];
    [remainingDaysArray release];
}

#pragma mark - TableView methods
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [orderedKeys objectAtIndex:section];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSArray *keys = [tableData allKeys];
    return [keys count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *key = [orderedKeys objectAtIndex:section];
    NSArray *values = [tableData objectForKey:key];
    return [values count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"BirthdayItemCell";
    
    BirthdayItemCell *cell = (BirthdayItemCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil){        
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"BirthdayItemCell" owner:nil options:nil];
        
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[BirthdayItemCell class]])
            {
                cell = (BirthdayItemCell *)currentObject;
                break;
            }
        }
    }
    NSString *key = [orderedKeys objectAtIndex:indexPath.section];
    NSArray *values = [tableData objectForKey:key];
    BirthdayItem *item = [values objectAtIndex:indexPath.row];
    [cell setupCell:item];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailedViewController *details = [[DetailedViewController alloc] initWithNibName:@"DetailedViewController" bundle:nil];
    NSString *key = [orderedKeys objectAtIndex:indexPath.section];
    NSArray *values = [tableData objectForKey:key];
    BirthdayItem *item = [values objectAtIndex:indexPath.row];
    details.item = item;
    [self.navigationController pushViewController:details animated:YES];
    [details release];
}

@end
